<template>
    <div class="box-content">
        <div class="navigation">内容管理/资讯内容</div>
        <!--搜索-->
        <div class="mt-3">
            <div>
                <el-input type="text" style="width: 200px;"  :clearable="true" class=" mrt-10" v-model="search.inputName" placeholder="输入关键字文件类型"></el-input>
                <el-button type="primary" class=" mrt-10" @click="onSearch">查询</el-button>
                <el-button type="primary" @click="openShanHu">新增</el-button>
            </div>
        </div>
        <!--表格-->
        <div class="mt-3">
            <el-table
                    :data="userData"
                    v-loading="loading"
                    align="center"
                    :element-loading-text="loadText"
                    :header-cell-style="tableHeaderColor"
                    stripe
                    style="width: 100%">
                <el-table-column
                        prop="id"
                        align="center"
                        label="编号"
                        width="100"
                >
                </el-table-column>
                <el-table-column
                        prop="title"
                        align="center"
                        label="标题"
                >
                </el-table-column>
                <el-table-column
                        prop="read_number"
                        align="center"
                        label="阅读量"
                >
                </el-table-column>
                <el-table-column
                        align="center"
                        label="icon"
                >
                    <template slot-scope="scope">
                        <div align="center"><img :src="scope.row['banner_url']" alt="" style="height: 50px;"></div>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="type_link.title"
                        align="center"
                        label="类型"
                >
                </el-table-column>
                <el-table-column
                        label="内容"
                >
                    <template slot-scope="scope">
                        <div style="width: 100px;overflow:hidden;text-overflow:ellipsis;white-space: nowrap;">{{scope.row['content']}}</div>
                    </template>
                </el-table-column>
                <el-table-column
                        label="创建日期"
                        align="center"
                        width="100">
                    <template slot-scope="scope">
                        <div align="center">{{scope.row['created_at']?scope.row['created_at'].slice(0, 11):'无'}}</div>
                        <div align="center">{{scope.row['created_at']?scope.row['created_at'].slice(11 ):'无'}}</div>
                    </template>
                </el-table-column>
                <el-table-column
                        label="状态/操作"
                        align="center"
                        fixed="right"
                        width="220"
                >
                    <template slot-scope="scope">
                        <el-button
                                size="mini"
                                type="primary"
                                @click="handleEdit(scope.row)">编辑
                        </el-button>
                        <el-button
                                size="mini"
                                type="danger"
                                @click="handleDelete(scope.row)">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="mt-3 float-right">
                <el-pagination
                        background
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="pageInfo.current_page"
                        :page-size="pageInfo.per_page"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="pageInfo.total">
                </el-pagination>
            </div>
        </div>
        <!--新增对话框-->
        <el-dialog :title="dialog.title"
                   :visible.sync="dialogFormVisible"
                   :close-on-click-modal="false"
                   width="80%">
            <el-form :model="form" :rules="rules" ref="form" label-width="110px" v-loading="loadingDialig">
                <el-form-item label="图标" prop="banner_url">
                    <el-upload v-loading="loadingDialig"
                               class="avatar-uploader"
                               action="123"
                               :show-file-list="false"
                               :before-upload="beforeAvatarUpload">
                        <img v-if="form.banner_url" :src="form.banner_url" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="标题" prop="title">
                    <el-input v-model="form.title" placeholder="请输入标题" style="width: 450px;"></el-input>
                </el-form-item>
                <el-form-item label="简介" prop="brief_info">
                    <el-input v-model="form.brief_info" placeholder="请输入简介" style="width: 450px;"></el-input>
                </el-form-item>
                <el-form-item label="类型" prop="type">
                    <el-select v-model="form.type" placeholder="请选择类型" style="width: 450px;">
                        <el-option
                                v-for="item in typeData"
                                :key="item.id"
                                :label="item.title"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="是否选中" prop="chosed">
                    <el-select v-model="form.chosed" placeholder="请选择排序" style="width: 450px;">
                        <el-option label="否" value="0"></el-option>
                        <el-option label="是" value="1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="内容" prop="content"  style="height: 510px;">
                    <quill-editor
                            style="height:450px;"
                            v-model="form.content"
                            ref="myQuillEditor"
                            :options="editorOption"
                            @change="onEditorChange($event)">
                    </quill-editor>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" v-if="!dialog.isEdit" :loading="loadingCreate" @click="submitCostomer('form')">{{loadingCreate?'创建中':'点击创建'}}</el-button>
                <el-button type="primary" v-if="dialog.isEdit"  :loading="loadingCreate" @click="submitCostomer('form')">{{loadingCreate?'修改中':'点击修改'}}</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import { quillEditor } from 'vue-quill-editor';
    import axios from 'axios';
    export default {
        name: "userList",
        data() {
            var validateName = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入文件类型'));
                }else{
                    callback();
                }
            };
            return {
                editorOption:{},
                editId: null,
                userInfo: {},
                pageInfo: {
                    per_page: 10,
                    total: 0,
                    current_page: 1
                },
                loadText: '数据加载中',
                userData: [],
                searchStr:'',
                search: {
                    roleStatus:'',
                    inputName:''
                },
                baseId: null,
                loading: false,
                loadingDialig: false,
                loadingCreate: false,
                dialogFormVisible: false,
                form: {
                    title:'',
                    type: '',
                    chosed: '0',
                    brief_info: '',
                    content: '',
                    banner_url:''
                },
                dialog: {
                    title: '',
                    isEdit: false
                },
                typeData:[],
                rules: {
                    title: [
                        { validator: validateName, trigger: 'change' }
                    ],
                    banner_url: [
                        { required: true, message: '请上传icon', trigger: 'change' }
                    ]
                }

            }
        },
        watch: {
            dialogFormVisible:function (val) {
                if (!val) {
                    Object.keys(this.form).forEach(key => this.form[key] = '');
                    this.$refs['form'].resetFields();
                    this.editId = null;
                    this.form.title = '';
                }
            }
        },
        created() {
            this.getTypeList();
            this.getCustomerList();
        },
        methods: {
            onEditorChange(val){//内容改变事件
                // console.info('内容改变事件',val);
                this.form.content = val.html;
            },
            getTypeList() {
                this.$http.get('api/admin/common/consultType')
                    .then((result) => {
                        this.typeData = result.data;
                    })
                    .catch((err) => {
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            beforeAvatarUpload (file) {
                var fileName=new Array()
                fileName =file.name.split('.');
                const extension = fileName[fileName.length-1] === 'jpg'
                const extension2 =  fileName[fileName.length-1]=== 'png'
                if (!extension && !extension2) {
                    this.$message({
                        message: '上传模板只能是jpg、png格式!',
                        type: 'warning'
                    });
                }
                if (extension || extension2) {
                    let fd = new FormData()
                    fd.append('fileUpload', file)
                    this.newImport(fd);
                }
                return false;
            },
            newImport (data) {
                let config = {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'Authorization' : 'Bearer' + localStorage.getItem('token')
                    }
                };
                this.loadingDialig = true;
                axios.post(process.env.VUE_APP_API_HOST + 'api/admin/common/uploadInfo', data,config)
                    .then((res) => {
                        this.form.banner_url = res.data.data.path;
                        this.loadingDialig = false;
                    })
                    .catch((err) => {
                        this.loadingDialig = false;
                        this.$message.warning(err.response.data.msg || "数据异常，请重试");
                    })
            },
            changeName(val) {
                this.search.inputName = val;
            },
            openShanHu(){
                this.dialog.title = '添加咨询内容';
                this.dialog.isEdit = false;
                this.dialogFormVisible = true;
            },
            getCustomerList() {
                this.loading = true;
                this.$http.get('api/admin/express/news' + this.searchStr, {
                    params: {
                        pageSize: this.pageInfo.per_page,
                        page: this.pageInfo.current_page
                    }
                })
                    .then((result) => {
                        this.userData = result.data;
                        this.pageInfo.total = result.meta.total;
                        this.loading = false;
                    })
                    .catch((err) => {
                        this.loading = false;
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            onSearch() {
                this.searchStr ="";
                if (this.search.inputName) {
                    this.addConStr();
                    this.searchStr += `title$=%${this.search.inputName}%`;
                }
                this.pageInfo.current_page = 1;
                this.getCustomerList();
            },
            addConStr() {
                if (this.searchStr.length > 0) {
                    this.searchStr += '&';
                } else {
                    this.searchStr += '?';
                }
            },
            submitCostomer(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.creatShanHu();
                    } else {
                        return false;
                    }
                });
            },
            creatShanHu(){
                this.loadingCreate = true;
                let params;
                if (this.dialog.isEdit) {
                    params={
                        title: this.form.title,
                        banner_url:this.form.banner_url,
                        chosed:this.form.chosed,
                        type:this.form.type,
                        content:this.form.content,
                        brief_info:this.form.brief_info
                    };
                    this.$http.put('api/admin/express/news/' + this.baseId, params)
                        .then((result) => {
                            this.$message({
                                type: 'success',
                                message: '修改成功!',
                                during:1000
                            });
                            this.dialogFormVisible = false;
                            this.loadingCreate = false;
                            this.getCustomerList();
                        })
                        .catch((err) => {
                            this.loadingCreate = false;
                            this.$message.warning(err.data.msg || "数据异常，请重试");
                        })
                } else {
                    params={
                        title: this.form.title,
                        banner_url:this.form.imageUrl,
                        chosed:this.form.chosed,
                        type:this.form.type,
                        content:this.form.content,
                        brief_info:this.form.brief_info
                    };
                    this.$http.post('api/admin/express/news', params)
                        .then((result) => {
                            this.$message({
                                type: 'success',
                                message: '添加成功!',
                                during:1000
                            });
                            this.dialogFormVisible = false;
                            this.loadingCreate = false;
                            this.getCustomerList();
                        })
                        .catch((err) => {
                            this.loadingCreate = false;
                            this.$message.warning(err.data.msg || "数据异常，请重试");
                        })
                }

            },
            handleEdit(val) {
                this.baseId = val.id;
                this.dialog.title = '编辑咨询内容';
                this.dialog.isEdit = true;
                this.dialogFormVisible = true;
                this.loadingDialig = true;
                this.$http.get('api/admin/express/news/' + val.id)
                    .then((result) => {
                        this.editId = result.data.id;
                        this.form.title = result.data.title;
                        this.form.banner_url = result.data.banner_url;
                        this.form.type = result.data.type;
                        this.form.brief_info = result.data.brief_info;
                        this.form.chosed = result.data.chosed.toString();
                        this.form.content = result.data.content;
                        this.loadingDialig = false;
                    })
                    .catch((err) => {
                        this.loadingDialig = false;
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            handleDelete(val) {
                this.$confirm('此操作将永久删除咨询内容, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$http.delete('api/admin/express/news/' + val.id)
                        .then((result) => {
                            this.$message({
                                type: 'success',
                                message: '咨询内容删除成功!',
                                during:1000
                            });
                            this.getCustomerList();
                        })
                        .catch((err) => {
                            this.$message.warning(err.data.msg || "数据异常，请重试");
                        })
                }).catch(() => {
                });
            },
            handleSizeChange(val) {
                this.pageInfo.current_page = 1;
                this.pageInfo.per_page = val;
                this.getCustomerList();
            },
            handleCurrentChange(val) {
                this.pageInfo.current_page = val;
                this.getCustomerList();
            },
            tableHeaderColor({row, column, rowIndex, columnIndex}) {
                if (rowIndex === 0) {
                    return 'background-color: #FAFAFA;color: #000;font-weight: 500;height:54px;font-size:14px'
                }
            }
        }
    }
</script>

<style lang="less"  scoped>
    .check-children{
        cursor: pointer;
    }
    .check-children:hover{
        color: #409EFF;
    }
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 50px;
        height: 50px;
        line-height: 50px;
        text-align: center;
    }
    .avatar {
        width: 50px;
        height: 50px;
        display: block;
    }
</style>